import moment from 'moment';
import store from '@/store';

/**
 * 获取当前时间是一年中第几周
 */
export const getYearWeek = () => {
  var currentDate = moment().format('YYYY-MM-DD');
  //当前日期
  var date1 = new Date(Number(currentDate.substring(0, 4)), parseInt(currentDate.substring(5, 7)) - 1, Number(currentDate.substring(8, 10)));
  //1月1号
  var date2 = new Date(Number(currentDate.substring(0, 4)), 0, 1);
  //获取1月1号星期（以周一为第一天，0周一~6周日）
  var dateWeekNum = date2.getDay() - 1;
  if (dateWeekNum < 0) {
    dateWeekNum = 6;
  }
  if (dateWeekNum < 5) {
    //前移日期
    date2.setDate(date2.getDate() - dateWeekNum);
  } else {
    //后移日期
    date2.setDate(date2.getDate() + 7 - dateWeekNum);
  }
  var d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);
  if (d < 0) {
    return this.getYearWeek();
  } else {
    //得到年数周数
    var week = Math.ceil((d + 1) / 7);
    if (Number(week) < 10) {
      return '0' + week;
    } else {
      if (week > 52) {
        return '01';
      } else {
        return week;
      }
    }
  }
};

/**
 * 生成GUID
 * @returns {string}
 */
export const guid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

/**
 * 获取当前两位年两位周
 */
export const getYearAndWeek = (currentDate) => {
  // 提取日期部分（年、月、日）
  const dateParts = currentDate.split(' ')[0].split('-');
  let year = dateParts[0];
  let month = dateParts[1];
  let day = dateParts[2];
  var date1 = new Date(year, parseInt(month) - 1, day),
    date2 = new Date(year, 0, 1),
    d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000),
    week = Math.ceil((d + (date2.getDay() + 1 - 1)) / 7);

  // 判断是否是闰年
  const isLeapYear = (year) => {
    return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  };

  // 修正周数，考虑闰年情况
  if (isLeapYear(year)) {
    if (date1.getMonth() === 0 && week > 52) {
      week = 1;
    }
  } else {
    if (week > 52) {
      week = 1;
    }
  }

  // 格式化周数
  if (week < 10) {
    return year.substring(year.length - 2) + '0' + week;
  } else {
    return year.substring(year.length - 2) + week;
  }
};

/**
 * 操作日志中显示成功日志
 * @param message
 */
export const showSuccessLog = (message) => {
  if (message) {
    //audio标签超过1000个会报错，并且播放不出，加这个判断超过500个时清空
    let audioLength = $('#operationLog').find('audio').length;
    if (audioLength >= 500) {
      $('#operationLog').children().remove();
    }
    if (message.indexOf('<') !== -1) {
      message = message.replace('<', '&lt;');
    } else if (message.indexOf('>') !== -1) {
      message = message.replace('>', '&gt;');
    }
    let logsp;
    if (message === null) {
      logsp = `<audio src="/audio/success.wav" autoplay="autoplay">Your browser does not support the audio tag.</audio>`;
    } else {
      let date = moment().format('YYYY/MM/DD HH:mm:ss');
      logsp = `<audio src="/audio/success.wav" autoplay="autoplay">Your browser does not support the audio tag.</audio>
                <p class="text-green">
                <span class="el-icon-success"></span>${message} ${date}
                </p>`;
    }
    $('#operationLog').eq(0).prepend(logsp);
  }
};

/**
 * 自定义提示音
 */
export const showVoiceLog = (message) => {
  const speech = new SpeechSynthesisUtterance(message); // 创建语音消息
  window.speechSynthesis.speak(speech);
};

/**
 * 操作日志中显示警告日志
 * @param message
 */
export const showWarningLog = (message) => {
  if (message) {
    //audio标签超过1000个会报错，并且播放不出，加这个判断超过500个时清空
    let audioLength = $('#operationLog').find('audio').length;
    if (audioLength >= 500) {
      $('#operationLog').children().remove();
    }
    if (message.indexOf('<') !== -1 || message.indexOf('>') !== -1) {
      message = message.replace(/</g, '&lt;');
      message = message.replace(/>/g, '&gt;');
    }
    let date = moment().format('YYYY/MM/DD HH:mm:ss');
    let logsp = `<audio src="/audio/fail.wav" autoplay="autoplay">Your browser does not support the audio tag.</audio>
            <p class="text-yellow">
            <span class="el-icon-warning"></span>${message} ${date}
            </p>`;
    $('#operationLog').eq(0).prepend(logsp);
  }
};
/**
 * 操作日志中显示失败日志
 * @param message
 */
export const showFailLog = (message) => {
  if (message) {
    //audio标签超过1000个会报错，并且播放不出，加这个判断超过500个时清空
    let audioLength = $('#operationLog').find('audio').length;
    if (audioLength >= 500) {
      $('#operationLog').children().remove();
    }
    if (!message.includes('<br>')) {
      if (message.indexOf('<') !== -1 || message.indexOf('>') !== -1) {
        message = message.replace(/</g, '&lt;');
        message = message.replace(/>/g, '&gt;');
      }
    }
    let date = moment().format('YYYY/MM/DD HH:mm:ss');
    let logsp = `<audio src="/audio/fail.wav" autoplay="autoplay">Your browser does not support the audio tag.</audio>
            <p class="text-red">
            <span class="el-icon-error"></span>${message} ${date}
            </p>`;
    $('#operationLog').eq(0).prepend(logsp);
  }
};

/**
 * 操作失败之后聚焦在当前操作的input输入框中
 * @param inputName
 */
export const selectInput = (inputName) => {
  $('[name=' + inputName + ']').trigger('select');
};
/**
 * 操作成功之后聚焦在下一个操作的input输入框中
 * @param inputName
 */
export const focusInput = (inputName) => {
  $('[name=' + inputName + ']').trigger('focus');
};

/**
 * 由下划线字符串转成驼峰
 * @param str
 */
export const getHump = (str) => {
  var arr = str.split('_');
  for (var i = 1; i < arr.length; i++) {
    arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].substring(1);
  }
  return arr.join('');
};

//科学计数法转换
export const ransferToNumber = (inputNumber) => {
  if (isNaN(inputNumber) || !inputNumber) {
    return inputNumber;
  }
  inputNumber = '' + inputNumber;
  inputNumber = parseFloat(inputNumber);
  let eformat = inputNumber.toExponential(); // 转换为标准的科学计数法形式（字符串）
  let tmpArray = eformat.match(/\d(?:\.(\d*))?e([+-]\d+)/); // 分离出小数值和指数值
  let number = inputNumber.toFixed(Math.max(0, (tmpArray[1] || '').length - tmpArray[2]));
  return number;
};

export function getMondayOfWeek(parmas) {
  const YYWW = parmas;
  // 解析年号和周号
  const yearString = YYWW.substr(0, 2);
  const weekString = YYWW.substr(2, 2);
  const year = 2000 + parseInt(yearString);
  const week = parseInt(weekString);

  // 计算对应年份的周一日期
  const monday = moment().year(year).isoWeek(week).startOf('isoWeek').format('YYYY-MM-DD');

  return monday;
}
